package com.kitty.mina.message;


import com.kitty.mina.annotation.MessageMeta;
import com.kitty.game.utils.ClassScanner;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//后加
import com.kitty.mina.message.Message;

public enum MessageFactory {

    /**
     * 枚举单例
     */
    INSTANCE;

    private Map<String, Class<?>> id2Clazz = new HashMap<>();

    private Map<Class<?>, String> clazz2Id = new HashMap<>();


    /**
     * scan all message class and register into pool
     */
    public void initMessagePool(String scanPath) {
        Set<Class<?>> messages = ClassScanner.listAllSubclasses(scanPath, Message.class);
        for (Class<?> clazz : messages) {
            MessageMeta meta = clazz.getAnnotation(MessageMeta.class);
            if (meta == null) {
                throw new RuntimeException("messages[" + clazz.getSimpleName() + "] missed MessageMeta annotation");
            }
            String key = buildKey(meta.module(), meta.cmd());
            if (id2Clazz.containsKey(key)) {
                //throw new RuntimeException("message meta [" + key + "] duplicate！！");
                continue;
            }
            id2Clazz.put(key, clazz);
            clazz2Id.put(clazz, key);
        }
    }


    public Class<?> getMessage(int module, int cmd) {
        return id2Clazz.get(buildKey(module, cmd));
    }

    public Class<?> getMessage(int id) {
        short module = (short) (id / 1000);
        short cmd = (short) (id % 1000);
        return id2Clazz.get(buildKey(module, cmd));
    }

    public String getMessageId(Class<?> clazz) {
        return clazz2Id.get(clazz);
    }

    private String buildKey(int module, int cmd) {
        return module + "_" + cmd;
    }

}
